package cn.bonoon.kernel.web.components;

import cn.bonoon.handler.impl.StandardAutoManager;
import cn.bonoon.kernel.annotations.QueryExpression;
import cn.bonoon.kernel.descriptors.UIClassDescriptor;
import cn.bonoon.kernel.descriptors.UIPropertyAccessor;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.annotations.AutoDataLoader;
import cn.bonoon.kernel.web.annotations.components.AsComboBox;
import cn.bonoon.kernel.web.annotations.components.AsComboGrid;
import cn.bonoon.kernel.web.annotations.components.AsComboTree;
import cn.bonoon.kernel.web.annotations.components.ComboMultipleChecker;
import cn.bonoon.kernel.web.annotations.components.OnReload;
import cn.bonoon.kernel.web.handlers.loader.ComboAutoLoaderHandler;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
import cn.bonoon.kernel.web.html.form.ComponentPropertyParser;

public abstract class AbstractComboComponent extends UIComponent{
	private final OnReload[] reloads;
	private String href;
	private boolean multiple;
	private final String value;
	protected AbstractComboComponent(String type, String value, ComponentPropertyParser componentParser, UIPropertyAccessor accessor, OnReload[] reloads){
		super(type, componentParser, accessor);
		this.reloads = reloads;
		this.value = value;
	}
	protected ComboAutoLoaderHandler handler;
	
	@Override
	protected void initComponent(UIPropertyBuilder builder) {
		AutoDataLoader autoLoader = accessor.getAnnotation(AutoDataLoader.class);
		if(null != autoLoader){
			StandardAutoManager manager = builder.getManager();
			try{
				handler = builderHandler(manager, autoLoader);
				if(null != handler){
					
					for(QueryExpression expression : autoLoader.queries()){
						handler.addExpression(expression);
					}
					
					//TODO 在这里需要把处理事件写保存回到控制器里
					manager.register(handler);
					this.multiple = handler.isMultiple();
					this.href = handler.getUrl();
				}
			}catch(Throwable t){
				t.printStackTrace();
			}
		}else{
			//没有使用AutoDataLoader的情况
			this.multiple = accessor.isAnnotationPresent(ComboMultipleChecker.class);
		}
		this.defaultValue = !this.multiple;
	}
//	protected void addQuery(String name){
//		if(null != handler){
//			handler.addQuery(name);
//		}
//	}
	@Override
	protected void initComponentAttribute(StringBuilder script, UIPropertyBuilder builder) {
		if(multiple)script.append(", multiple:true");
		if(reloads.length > 0){
			//TODO 下面的应该删掉吧,好像这种方式的使用也不是很大
			UIClassDescriptor descriptor = accessor.getDescriptor();
			script.append(",onChange:function(nv, ov){");
			for (int i = 0; i < reloads.length; i++) {
				OnReload rl = reloads[i];
				if(rl.isScript()){
					//直接添加脚本
					script.append(rl.value());
				}else{
					UIPropertyAccessor pa = descriptor.get(rl.value());
					if(null != pa){
						//允许动态联动的控件有：AsComboBox/AsComboGrid/AsComboTree
						AsComboBox cb = pa.getAnnotation(AsComboBox.class);
						if(null != cb){
							script.append("jQuery('#").append(rl.value()).append("').buppancombo('reload',jQuery('#").append(rl.value());
							script.append("').data('data-loader-url')+'&").append(rl.argName()).append("='+nv+'&_='+Math.random());");
							continue;
						}
						AsComboTree ct = pa.getAnnotation(AsComboTree.class);
						if(null != ct){
							script.append("jQuery('#").append(rl.value()).append("').buptreecombo('reload',jQuery('#").append(rl.value());
							script.append("').data('data-loader-url')+'&").append(rl.argName()).append("='+nv+'&_='+Math.random());");
							continue;
						}
						AsComboGrid cg = pa.getAnnotation(AsComboGrid.class);
						if(null != cg){
							script.append("jQuery('#").append(rl.value()).append("').bupgridcombo('grid').bupgrid('reload', {").append(rl.argName()).append(":nv});");
							continue;
						}
					}
				}
			}
			script.append("}");
		}
		
		//String binName = builder.getBindedName();
//		if (StringHelper.isEmpty(href)) {
//			href = builder.path(value);
//		}
//		script.append(", url:'").append(href).append(href.indexOf('?') == -1 ? "?" : "&").append(componentName)
//		.append("=$!{").append(binName).append(".id}'");
	}
	
	protected abstract ComboAutoLoaderHandler builderHandler(StandardAutoManager manager, AutoDataLoader autoLoader)throws Throwable;
	
	@Override
	protected void initInputAttribute(StringBuilder html, StringBuilder settings, UIPropertyBuilder builder) {
		super.initInputAttribute(html, settings, builder);
		if (StringHelper.isEmpty(href)) {
			if(null != value && value.startsWith("/")){
				href = builder.path(value);
			}else{
				href = value;
			}
		}
		html.append(" url='").append(href).append(href.indexOf('?') == -1 ? "?" : "&").append(componentName)
		.append("=$!{").append(builder.getBindedName()).append(".id}'");

		//这里需要把默认的处理路径存到body对象上
//		builder.getInitBlock().append("jQuery('#").append(componentId).append("').data('data-loader-url', jQuery('#").append(componentId)
//				.append("').").append(type).append("('settings')['url']);"); // options
	}
	
}
